#include "AcSwitchDetector.h"

#include "LoopManager.h"
#include "ConfigManager.h"


AcSwitchDetector::AcSwitchDetector(DummyChannel& channel, const ExtendDeviceType& deviceType, const std::string& deviceActknowlege): ExtendDevice(channel, deviceType, deviceActknowlege), mloopManager(LoopManagerSingleton::instance()) {

}


bool AcSwitchDetector::updateInformation() {
    const std::string commandString("<SWITCH_STATUS>");
    std::string result;
    bool status = false;
    try {
        mchannel.sendStringReturnString(commandString, result);
        status = true;
        if ("<SWITCH_STATUS_ERROR>" != result) {
            mresponseString = result.substr(commandString.size(), result.size() - commandString.size() - 1);
        }

    } catch (std::exception& ex) {
        LOG_ERROR(ex.what());
    }

    return status;
}


bool AcSwitchDetector::initialize() noexcept {
    mconfigInfo = ConfigManagerSingleton::instance().getExtendDeviceConfig().switchDetectorInfo;

    return true;
}


//bool AcSwitchDetector::recheck() {
//    bool checkResult = updateInformation();
//    if (checkResult && mchanged) {
//        parseSwitchStatus();
//    }
//    mchanged = false;
//
//    return checkResult;
//}



bool  AcSwitchDetector::analysisSwitchStatus(const std::string& loopStatus) {
    bool result = false;

    if (mswitchString == mresponseString) {
        return result;
    }
    mswitchString = mresponseString;

    std::string buffer = loopStatus;
    /*
    mswitchMode = mswitchString.substr(0, 4);
    mloopSwitchStatus = mswitchString.substr(4);
    */
    mloopSwitchStatus = mswitchString;

    const std::string::size_type switchSize = mloopSwitchStatus.size();
    char* pchar = nullptr;
    std::string::size_type size = std::min(mconfigInfo.loopSwitchMap.size(), buffer.size());
    for (std::string::size_type i = 0; i < size; ++i) {
        pchar = &buffer[i];
        for (auto& refIndex : mconfigInfo.loopSwitchMap[i]) {
            if (switchSize > refIndex) {
                pchar = &mloopSwitchStatus[refIndex];
                if ((buffer[i] & 1) != (*pchar - 48)) {
//                    *pchar += 5;
//                    result = true;
                }
            }
        }
    }

    result = true;

    return result;
}



